package com.ruoyi.web.controller.cpsp;/*
    @author neu.xiangwenjuan
    @create 2023/3/14
*/

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.mapper.DepartmentMapper;
import com.ruoyi.cpsp.mapper.PreviousPerformanceDataMapper;
import com.ruoyi.cpsp.mapper.TeamGroupMapper;
import com.ruoyi.cpsp.service.*;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/cpsp/previous")
public class PreviousPerformanceDataController {

    @Autowired
    private PreviousPerformanceDataService previousPerformanceDataService;

    @Autowired
    private PreviousPerformanceDataMapper previousPerformanceDataMapper;

    @Autowired
    private CurrentPerformanceDataService currentService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private EvaluateRecordDetailService detailService;
    // 查询信息，往季度的数据返回到前端展示
    /**
     * 分页显示，一次几条数据。
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("获得以往季度人员绩效信息")
    @RequestMapping(value = "/getPreviousPerformanceData", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getPreviousPerformanceData(@RequestParam(defaultValue = "1") Integer pageNum,
                                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                                 @RequestParam Integer year,
                                                 @RequestParam Integer quarter) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        List<String> idCardList = employeeService.selectCardByDepart(dept.getDeptName(), 0);

        PageHelper.startPage(pageNum,pageSize);
        List<PreviousPerformanceDataEn> previousPerformanceDataEns = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            previousPerformanceDataEns = previousPerformanceDataService.selectAll(year, quarter);
        }else if (role.equals("department")){
            previousPerformanceDataEns = previousPerformanceDataService.selectDataByIdCard(year, quarter, idCardList);
        }
        PageInfo pageInfo = PageInfo.of(previousPerformanceDataEns);

        return AjaxResult.success(pageInfo);
    }

    // 添加数据，当本季度结束时，将current_performance_data中数据添加到该表中。
    // 定时任务，每季度的开始1号执行。写在tool/TimingTaskImpl.java中

    /**
     * 筛选条件：年份、季度，班组，身份证号，姓名。部门登录，需要获取本部门的信息。
     */
    /**
     *
     * @param pageNum
     * @param pageSize
     * @param year
     * @param quarter
     * @param department 管理员登陆时，根据部门筛选
     * @param teamGroup 根据班组筛选
     * @param employeeInfo 根据员工姓名或者身份证号
     * @return
     */
    @ApiOperation("筛选获得当前季度人员绩效信息")
    @RequestMapping(value = "/getPreviousPerformanceDataSelect", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getPreviousPerformanceDataSelect(@RequestParam(defaultValue = "1") Integer pageNum,
                                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                                       @RequestParam(required = false) Integer year,
                                                       @RequestParam(required = false) Integer quarter,
                                                       @RequestParam(required = false) String department,
                                                       @RequestParam(required = false) Integer teamGroup,
                                                       @RequestParam(required = false) String employeeInfo){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();

        PageInfo<PreviousPerformanceDataEn> source = new PageInfo<>();

        String departId = department == null ? "" : department;
        Integer teamId = teamGroup == null ? 0 : teamGroup;
        String employeeIn = employeeInfo == null ? "" : employeeInfo;

        List<PreviousPerformanceDataEn> previousPerformanceDataEns = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                previousPerformanceDataService.selectSelective(quarter,year,departId, teamId, employeeIn);
            });
            previousPerformanceDataEns = new ArrayList<>(source.getList());
        }else if (role.equals("department")) {
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                previousPerformanceDataService.selectSelective(quarter, year, departmentId, teamId, employeeIn);
            });
            previousPerformanceDataEns = new ArrayList<>(source.getList());
        }
        PageInfo<PreviousPerformanceDataEn> target = new PageInfo<>();
        BeanUtils.copyProperties(source, target);
        target.setList(previousPerformanceDataEns);
        return AjaxResult.success(target);
    }

    @ApiOperation("导出某年份某季度绩效信息")
    @RequestMapping(value = "/loadPreviousPerformance", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult loadPreviousPerformance(Integer year, Integer quarter) {
        // 获取登录人的身份和个人信息。
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();

        ArrayList<PreviousInfoDepart> result = new ArrayList<>();
        List<Department> departments = departmentService.selectAll();
        if (role.equals("department")) {
            Department department = departmentMapper.selectByDepartmentId(departmentId);
            PreviousInfoDepart depart = getPerformanceByDepart(departmentId, department.getDepartmentName(), year, quarter);
            result.add(depart);
        }else if(role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            PreviousInfoDepart depart = new PreviousInfoDepart();
            for (Department department:departments) {
                depart = getPerformanceByDepart(department.getDepartmentId(), department.getDepartmentName(),year , quarter);
                result.add(depart);
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("添加历史数据")
    @PostMapping("/insertPreviousPerformance")
    public AjaxResult insertPreviousPerformance(@RequestBody PreviousPerformanceData previousPerformanceData){
        try {
            int length = previousPerformanceDataService.selectPreviousIsEmpty(previousPerformanceData.getYear(), previousPerformanceData.getQuarter(), previousPerformanceData.getEmployeeIdCard()).size();
            System.out.println(length);
            if (previousPerformanceDataService.selectPreviousIsEmpty(previousPerformanceData.getYear(), previousPerformanceData.getQuarter(), previousPerformanceData.getEmployeeIdCard()).size() > 0) {
                return AjaxResult.error("已存在该员工的数据，不能重复添加！");
            }
            if (previousPerformanceData.getOnWork() < 45){
                previousPerformanceData.setIncreaseBase(0.0);
            }
            previousPerformanceData.setValueOfPunishment((previousPerformanceData.getCumulativeBase() + previousPerformanceData.getIncreaseBase()) * previousPerformanceData.getProportionOfPunishment());
            previousPerformanceData.setCurrentBase(previousPerformanceData.getCumulativeBase() + previousPerformanceData.getIncreaseBase() - previousPerformanceData.getValueOfPunishment());
            previousPerformanceData.setMoneyEveryMonth(previousPerformanceData.getCurrentBase());
            previousPerformanceData.setMoneyQuarter(3 * previousPerformanceData.getMoneyEveryMonth());
            // 该季度累积绩效：currentBase，将该员工的下一个季度的绩效更新，将上季度绩效值赋值为当前季度的绩效结果。09:44:58.248
            // 如果是添加的上个季度的数据，或者更新上个季度的数据，那么下个季度的数据也需要更新。
            if(previousPerformanceDataMapper.insert(previousPerformanceData) == 1){
                if (previousPerformanceDataService.updatePreviousData(previousPerformanceData)) {
                    return AjaxResult.success();
                }else {
                    return AjaxResult.error();
                }
            }
            return AjaxResult.error();
        }catch (NullPointerException e) {
            return AjaxResult.error("请输入在岗天数等内容！");
        }catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("更新历史数据")
    @PutMapping("/updatePreviousPerformance")
    public AjaxResult updatePreviousPerformance(@RequestParam Integer id,
                                                @RequestParam Integer year,
                                                @RequestParam Integer quarter,
                                                @RequestParam String employee_idCard,
                                                @RequestParam double cumulativeBase,
                                                @RequestParam double propOfPunishment,
                                                @RequestParam Integer onWork,
                                                @RequestParam(required = false) String annotation) {
        PreviousPerformanceData previousPerformanceData = previousPerformanceDataMapper.selectById(id);
        previousPerformanceData.setCumulativeBase(cumulativeBase);
        previousPerformanceData.setProportionOfPunishment(propOfPunishment);

        if (onWork < 45 || (detailService.selectDetailByEmployeeYear(employee_idCard, year, quarter).size() >= 1)){
            previousPerformanceData.setIncreaseBase(0.0);
        }else {
            boolean isDirect = employeeService.getIsDirectProducer(employee_idCard);
            if (isDirect) {
                if ((cumulativeBase + 100.0) > 1000) {
                    previousPerformanceData.setIncreaseBase(1000 - cumulativeBase);
                }else {
                    previousPerformanceData.setIncreaseBase(100.0);
                }
            }else {
                if ((cumulativeBase + 50.0) > 500) {
                    previousPerformanceData.setIncreaseBase(500 - cumulativeBase);
                }else {
                    previousPerformanceData.setIncreaseBase(50.0);
                }
            }
        }
        previousPerformanceData.setValueOfPunishment((cumulativeBase + previousPerformanceData.getIncreaseBase()) * propOfPunishment);
        previousPerformanceData.setCurrentBase(cumulativeBase + previousPerformanceData.getIncreaseBase() - previousPerformanceData.getValueOfPunishment());
        previousPerformanceData.setMoneyEveryMonth(previousPerformanceData.getCurrentBase());
        previousPerformanceData.setMoneyQuarter(3 * previousPerformanceData.getMoneyEveryMonth());
        previousPerformanceData.setOnWork(onWork);
//        System.out.println(previousPerformanceData);
        previousPerformanceData.setAnnotation(annotation);
        if(previousPerformanceDataMapper.updateById(previousPerformanceData) == 1){
            return AjaxResult.success();
//            if (previousPerformanceDataService.updatePreviousData(previousPerformanceData)) {
//                return AjaxResult.success();
//            }else {
//                return AjaxResult.error();
//            }
        }
        return AjaxResult.error();
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("根据上一季度添加下一季度的初始值(2022)")
    @PostMapping("/initNextQuarter")
    public AjaxResult initNextQuarter(@RequestParam Integer year, @RequestParam Integer quarter){
        Integer lastYear = quarter==1 ? year-1 : year;
        Integer lastQuarter = quarter==1 ? 4 : quarter-1;
        QueryWrapper<PreviousPerformanceData> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("year",year).eq("quarter",quarter);
        List<PreviousPerformanceData> data = previousPerformanceDataMapper.selectList(wrapper1);
        if(data.size() > 0){
            return AjaxResult.error("该季度历史记录已经生成，请勿重复生成！");
        }
        QueryWrapper<PreviousPerformanceData> wrapper = new QueryWrapper<>();
        wrapper.eq("year",lastYear).eq("quarter",lastQuarter);
        List<PreviousPerformanceData> previousPerformanceDataList = previousPerformanceDataMapper.selectList(wrapper);
        for(PreviousPerformanceData previousPerformanceData:previousPerformanceDataList){
            previousPerformanceData.setId(null);
            previousPerformanceData.setYear(year);
            previousPerformanceData.setQuarter(quarter);
            previousPerformanceData.setCumulativeBase(previousPerformanceData.getCurrentBase());
            previousPerformanceData.setEvaluateRecordId("");
            boolean isDirect = employeeService.getIsDirectProducer(previousPerformanceData.getEmployeeIdCard());
            if (isDirect) {
                previousPerformanceData.setIncreaseBase(100.0);
            }else {
                previousPerformanceData.setIncreaseBase(50.0);
            }
            previousPerformanceData.setProportionOfPunishment(0.0);
            previousPerformanceData.setValueOfPunishment(0.0);
            double currentBase = previousPerformanceData.getCumulativeBase() + previousPerformanceData.getIncreaseBase();
            previousPerformanceData.setCurrentBase(currentBase);
            previousPerformanceData.setMoneyEveryMonth(currentBase);
            previousPerformanceData.setMoneyQuarter(currentBase * 3);
            previousPerformanceData.setOnWork(0);
            previousPerformanceDataMapper.insert(previousPerformanceData);
        }
        return AjaxResult.success();
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("获得绩效总值")
    @GetMapping(value = "/getPreviousPerformanceSum")
    public AjaxResult getPreviousPerformanceSum(@RequestParam(required = false) String departmentId,
                                               @RequestParam(required = false) Integer year,
                                               @RequestParam(required = false) Integer quarter) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        double sum = 0.0;
        boolean r = role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin");
        if(r){
            if(departmentId.equals("") && quarter==0 && year==0){
                sum = previousPerformanceDataMapper.selectSum1();
            }else if(departmentId.equals("") && quarter==0){
                sum = previousPerformanceDataMapper.selectSum2(year);
            }else if(quarter==0 && year==0){
                List<String> idCards = employeeService.selectCardByDepart(departmentId, 0);
                sum = idCards.size() == 0 ? 0 : previousPerformanceDataMapper.selectSum3(idCards);
            }else if(departmentId.equals("") && year==0){
                return AjaxResult.error("参数错误");
            }else if(departmentId.equals("")){
                sum = previousPerformanceDataMapper.selectSum4(year, quarter);
            }else if(year==0){
                List<String> idCards = employeeService.selectCardByDepart(departmentId, 0);
                sum = idCards.size() == 0 ? 0 : previousPerformanceDataMapper.selectSum5(idCards, quarter);
            }else if(quarter==0){
                List<String> idCards = employeeService.selectCardByDepart(departmentId, 0);
                sum = idCards.size() == 0 ? 0 : previousPerformanceDataMapper.selectSum6(idCards, year);
            }else{
                List<String> idCards = employeeService.selectCardByDepart(departmentId, 0);
                sum = idCards.size() == 0 ? 0 : previousPerformanceDataMapper.selectSum7(idCards, year, quarter);
            }
        }else if(role.equals("department")){
            List<String> idCardList = employeeService.selectCardByDepart(departmentId, 0);
            if (idCardList.size() == 0) {
                sum = 0;
            }else {
                if(year==0 && quarter==0){
                    sum = previousPerformanceDataMapper.selectSum3(idCardList);
                }else if(year==0){
                    sum = previousPerformanceDataMapper.selectSum5(idCardList, quarter);
                }else if(quarter==0){
                    sum = previousPerformanceDataMapper.selectSum6(idCardList, year);
                }else{
                    sum = previousPerformanceDataMapper.selectSum7(idCardList, year, quarter);
                }
            }
        }else{
            return AjaxResult.error("权限错误");
        }
        return AjaxResult.success(sum);
    }

    private PreviousInfoDepart getPerformanceByDepart(String departmentId, String departmentName, Integer year, Integer quarter) {
        List<PreviousPerformanceDataEn> list = previousPerformanceDataService.selectSelective(quarter, year, departmentId, null, null);
        PreviousInfoTeam team = new PreviousInfoTeam();
        team.setTeamGroupName("总表");
        team.setDataList(list);
        team.setTotal(previousPerformanceDataService.selectDataTotal(quarter, year, departmentId, null));

        ArrayList<PreviousInfoTeam> teams = new ArrayList<>();
        teams.add(team);

        List<TeamGroup> teamGroupList = teamGroupMapper.findTeamGroupByDepart(departmentId);
        for (TeamGroup teamGroup: teamGroupList) {
            List<PreviousPerformanceDataEn> teamList = previousPerformanceDataService.selectSelective(quarter, year, departmentId, teamGroup.getId(), null);
            CurrentPerformanceTotal teamTotal = previousPerformanceDataService.selectDataTotal(quarter, year, departmentId, teamGroup.getId());
            PreviousInfoTeam team1 = new PreviousInfoTeam();
            team1.setDataList(teamList);
            team1.setTeamGroupName(teamGroup.getTeamGroupName());
            team1.setTotal(teamTotal);
            teams.add(team1);
        }
        PreviousInfoDepart depart = new PreviousInfoDepart();
        depart.setDepartmentName(departmentName);
        depart.setDepartList(teams);
        return depart;
    }


    @ApiOperation("删除某条历史数据")
    @RequestMapping(value = "/deletePreviousPerformanceInfo", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult deletePreviousPerformanceInfo(@RequestParam(required = false) Integer year,
                                                    @RequestParam(required = false) Integer quarter,
                                                    @RequestParam(required = false) String employeeIdCard) {
        if (previousPerformanceDataService.deletePreviousPerformanceInfo(year, quarter, employeeIdCard) > 0) {
            return AjaxResult.success("删除成功！");
        }
        return AjaxResult.error();
    }
}

